package com.hopu.v1.service.front.question.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopu.v1.mapper.front.question.FErrorNotebookOptionsMapper;
import com.hopu.v1.mapper.front.question.FErrorNotebooksQuestionsMapper;
import com.hopu.v1.pojo.question.*;
import com.hopu.v1.service.front.question.FQuestionsService;
import com.hopu.v1.mapper.front.question.FQuestionsMapper;
import com.hopu.v1.vo.JudgeQuestionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.Transient;
import java.util.*;

/**
 *
 */
@Service
public class FQuestionsServiceImpl extends ServiceImpl<FQuestionsMapper, Questions>
    implements FQuestionsService {

    @Autowired
    private FQuestionsMapper fQuestionsMapper;

    @Autowired
    private FErrorNotebooksQuestionsMapper fErrorNotebooksQuestionsMapper;

    @Autowired
    private FErrorNotebookOptionsMapper fErrorNotebookOptionsMapper;

    @Transient
    @Override
    public JudgeQuestionVo judgeQuestion(String studentId, int questionId, String studentAnswer) {
        JudgeQuestionVo judgeQuestionVo = new JudgeQuestionVo();
        //查询题目
        Questions qurryQuestions = new Questions();
        qurryQuestions.setId(questionId);
        List<Questions> questions = fQuestionsMapper.selectAllByQuestionsBanksId(qurryQuestions);
        Questions qs = questions.get(0);
        judgeQuestionVo.setQuestions(qs);
        //值判断单选题、多选题以及判断题
        if(qs.getQuestionType().equals("0")  || qs.getQuestionType().equals("2")){
            for (QuestionsOptions option : qs.getOptions()) {
                if (option.getStatus().equals(1)){
                    if ((option.getId()+"").equals(studentAnswer)){
                        judgeQuestionVo.setMessage("回答正确");
                        return judgeQuestionVo;
                    }else {
                        String answer ="";
                        for (QuestionsOptions qsOption : qs.getOptions()) {
                            if((qsOption.getId()+"").equals(studentAnswer)){
                                answer = qsOption.getOptionTitle();
                                break;
                            }
                        }
                        LambdaQueryWrapper<ErrorNotebooksQuestions> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(ErrorNotebooksQuestions::getStudentId,studentId);
                        queryWrapper.eq(ErrorNotebooksQuestions::getErrorQuestion,qs.getQuestionTitle());
                        queryWrapper.eq(ErrorNotebooksQuestions::getErrorSource,0);
                        ErrorNotebooksQuestions one = fErrorNotebooksQuestionsMapper.selectOne(queryWrapper);
                        if(one==null){
                            ErrorNotebooksQuestions errorNotebooksQuestions = new ErrorNotebooksQuestions(studentId,0,qs.getQuestionTitle(),qs.getQuestionType(),answer,0);
                            fErrorNotebooksQuestionsMapper.insert(errorNotebooksQuestions);
                            for (QuestionsOptions qsOption : qs.getOptions()) {
                                fErrorNotebookOptionsMapper.insert(new ErrorNotebookOptions(null,errorNotebooksQuestions.getId(),qsOption.getOptionTitle(),qsOption.getOptionDescribe(),qsOption.getStatus()+"",null,null));
                            }
                        }else {
                            ErrorNotebooksQuestions questions1 = new ErrorNotebooksQuestions();
                            questions1.setStatus(0);
                            questions1.setStudentAnswer(answer);
                            fErrorNotebooksQuestionsMapper.update(questions1,new LambdaQueryWrapper<ErrorNotebooksQuestions>().eq(ErrorNotebooksQuestions::getId,one.getId()));
                        }
                        judgeQuestionVo.setMessage("回答错误");
                        return judgeQuestionVo;
                    }
                }
            }
        }else if (qs.getQuestionType().equals("1")){
            //多选题
            String[] split = studentAnswer.split(",");
            int trueCount = 0; //正确选项个数
            int studentTrueCount = 0; //学生正确选项个数
            StringBuffer answer = new StringBuffer();
            for (QuestionsOptions option : qs.getOptions()) {
                if ((option.getStatus()+"").equals("1")){
                    trueCount++;
                    for (String s : split) {
                        if (s.equals(option.getId()+"")){
                            answer.append(option.getOptionTitle()).append(",");
                            studentTrueCount++;
                        }
                    }
                }else{
                    for (String s : split) {
                        if (s.equals(option.getId()+"")){
                            answer.append(option.getOptionTitle()).append(",");
                        }
                    }
                }
            }
            String answer1 = answer.substring(0,answer.length()-1);
            if (studentTrueCount==trueCount&&split.length==trueCount){
                judgeQuestionVo.setMessage("回答正确");
                return judgeQuestionVo;
            }else {
                LambdaQueryWrapper<ErrorNotebooksQuestions> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(ErrorNotebooksQuestions::getStudentId,studentId);
                queryWrapper.eq(ErrorNotebooksQuestions::getErrorQuestion,qs.getQuestionTitle());
                queryWrapper.eq(ErrorNotebooksQuestions::getErrorSource,0);
                ErrorNotebooksQuestions one = fErrorNotebooksQuestionsMapper.selectOne(queryWrapper);
                if (one==null){
                    ErrorNotebooksQuestions errorNotebooksQuestions = new ErrorNotebooksQuestions(studentId,0,qs.getQuestionTitle(),qs.getQuestionType(), answer1,0);
                    fErrorNotebooksQuestionsMapper.insert(errorNotebooksQuestions);
                    for (QuestionsOptions qsOption : qs.getOptions()) {
                        fErrorNotebookOptionsMapper.insert(new ErrorNotebookOptions(null,errorNotebooksQuestions.getId(),qsOption.getOptionTitle(),qsOption.getOptionDescribe(),qsOption.getStatus()+"",null,null));
                    }
                }else {
                    ErrorNotebooksQuestions questions1 = new ErrorNotebooksQuestions();
                    questions1.setStatus(0);
                    questions1.setStudentAnswer(answer1);
                    fErrorNotebooksQuestionsMapper.update(questions1,new LambdaQueryWrapper<ErrorNotebooksQuestions>().eq(ErrorNotebooksQuestions::getId,one.getId()));
                }
                judgeQuestionVo.setMessage("回答错误");
                return judgeQuestionVo;
            }
        } else {
            judgeQuestionVo.setMessage("该题类型不支持判断");
            return judgeQuestionVo;
        }
        return null;
    }

    @Override
    public List<ErrorNotebooksQuestions> queryErrQuestions(String studentId, int questionsCount) {
        ErrorNotebooksQuestions errorNotebooksQuestions = new ErrorNotebooksQuestions();
        errorNotebooksQuestions.setStudentId(studentId);
        errorNotebooksQuestions.setStatus(0);
        List<ErrorNotebooksQuestions> errorList = fErrorNotebooksQuestionsMapper.selectAllByErrQuestion(errorNotebooksQuestions);
        if (errorList.size() == 0){
            return null;
        } else if (errorList.size() <= questionsCount){
            return errorList;
        }else {
            //抽取的题目id数组
            int[] qids = new int[questionsCount];
            //生成随机题目
            Random random = new Random();
            //获取所有题目id
            List<ErrorNotebooksQuestions> ids = new ArrayList<>();
            for (int i = 0; i < questionsCount; i++) {
                int raNum = random.nextInt(errorList.size());
                ids.add(errorList.get(raNum));
                ids.remove(errorList.get(raNum));
                if (ids.size()==questionsCount){
                    break;
                }
            }
            return ids;
        }
    }

    @Override
    public List<Questions> queryQuestions(int[] questionBankIds,Integer questionsCount,Integer subjectId) {
        if (questionBankIds==null){
            Questions questions = new Questions();
            questions.setStatus(1);
            return fQuestionsMapper.selectAllBySubjectId(subjectId,questions);
        }
        //抽取的题目id数组
        int[] qids = new int[questionsCount];
        //生成随机题目
        Random random = new Random();
        if (questionBankIds.length==1){
            Long l = fQuestionsMapper.selectCount(new LambdaQueryWrapper<Questions>().eq(Questions::getQuestionBanksId, questionBankIds[0]));
            if (l==0){
                return null;
            }
            if (l<=questionsCount){
                Questions questions = new Questions();
                questions.setQuestionBanksId(String.valueOf(questionBankIds[0]));
                questions.setStatus(1);
                return fQuestionsMapper.selectAllByQuestionsBanksId(questions);
            }else{
                //获取所有题目id
                Questions questions = new Questions();
                questions.setQuestionBanksId(String.valueOf(questionBankIds[0]));
                questions.setStatus(1);
                List<Integer> ids = fQuestionsMapper.selectAllIdByQuestionsBanksIds(questions);
                for (int i = 0; i < questionsCount; i++) {
                    int ra =random.nextInt(ids.size());
                    qids[i] = ids.get(ra);
                    //防止随机题目重复，已经添加的题号，在题库序号中就移除
                    ids.remove(ra);
                }
                return fQuestionsMapper.selectAllById(qids,questions);
            }
        }else if (questionBankIds.length > 1 && questionBankIds.length <= questionsCount){
            //平均每个题库抽取题目，题库的数量
            int len = questionBankIds.length;
            //题库ids
            Set<Integer> setIds = new HashSet<>();
            //每个题库的id集合的集合
            ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
            for (int i = 0; i < len; i++) {
                Questions questions = new Questions();
                questions.setQuestionBanksId(String.valueOf(questionBankIds[i]));
                questions.setStatus(1);
                List<Integer> ids = fQuestionsMapper.selectAllIdByQuestionsBanksIds(questions);
                //如果该题库下没有题目返回该题目id
                if (ids.isEmpty()) {
                    Questions questionsNull = new Questions();
                    questionsNull.setQuestionBanksId(String.valueOf(questionBankIds[i]));
                    ArrayList<Questions> list = new ArrayList<>();
                    list.add(questionsNull);
                }
                lists.add((ArrayList<Integer>) ids);
            }
            boolean flag = false;
            while (true){
                //题目数量足够跳出
                if (setIds.size() == questionsCount || flag){
                    break;
                }
                //记录非空题库数量
                int size = lists.size();
                for (ArrayList<Integer> list : lists) {
                    if (list.size() == 0){
                        size--;
                        continue;
                    }
                    int ra = random.nextInt(list.size());
                    setIds.add(list.get(ra));
                    //防止随机题目重复，已经添加的题号，在题库序号中就移除
                    list.remove(ra);
                    if (setIds.size() == questionsCount){
                        flag = true;
                        break;
                    }
                }
                //如果非空题库数量为0，则跳出循环，意味着出现每个题库题目出完了
                if (size == 0)
                    break;
            }
            //将set集合转成数组
            int index = 0;
            for (Integer setId : setIds) {
                qids[index++] = setId;
            }
            Questions questions = new Questions();
            questions.setQuestionBanksId(String.valueOf(questionBankIds[0]));
            questions.setStatus(1);
            System.out.println(Arrays.toString(qids));
            return fQuestionsMapper.selectAllById(qids,questions);
        }
        return null;
    }

    @Override
    public List<Questions> queryQuestionList(Integer questionBankId,Integer status) {
        LambdaQueryWrapper<Questions> wrapper = new LambdaQueryWrapper<>();
        if (status!= null){
            wrapper.eq(Questions::getQuestionType,status);
        }
        if (questionBankId != null){
            wrapper.eq(Questions::getQuestionBanksId,questionBankId);
        }
        return fQuestionsMapper.selectList(wrapper);
    }

    @Override
    public List<Questions> selectStudentAndComment(Questions questions) {
        return fQuestionsMapper.selectStudentAndComment(questions);
    }

    @Override
    public List<Questions> selectStudentComment(Questions questions) {
        return fQuestionsMapper.selectStudentComment(questions);
    }

    //            //第一个题库 如果题目数量或者题库数量计算除不尽 则少抽取一个
//            int first = questionsCount/len;
//            //剩下的题库题目平均抽取
//            int last = questionsCount-first;
//
//            //获取所有题目id 第一个题库
//            Questions questions = new Questions();
//            questions.setQuestionBanksId(String.valueOf(questionBankIds[0]));
//            questions.setStatus(1);
//            List<Integer> ids = fQuestionsMapper.selectAllIdByQuestionsBanksIds(questions);
//
//            for (int i = 0; i < first; i++) {
//                int ra =random.nextInt(ids.size());
//                qids[i] = ids.get(ra);
//                //防止随机题目重复，已经添加的题号，在题库序号中就移除
//                ids.remove(ra);
//                System.out.println("Fqids = " + qids[i]);
//            }
//            //获取所有题目id 剩余的题库
//            //记录当前题库索引
//            int index = 1;
//            for (int i = 0; i < last; i++) {
//                Questions questionsIndex = new Questions();
//                questionsIndex.setQuestionBanksId(String.valueOf(questionBankIds[index]));
//                questionsIndex.setStatus(1);
//                ids = fQuestionsMapper.selectAllIdByQuestionsBanksIds(questionsIndex);
//                //如果该题库下没有题目返回该题目id
//                if (ids.isEmpty()){
//                    Questions questionsNull = new Questions();
//                    questionsNull.setQuestionBanksId(String.valueOf(questionBankIds[index]));
//                    ArrayList<Questions> list = new ArrayList<>();
//                    list.add(questionsNull);
//                    return list;
//                }
//                int ra =random.nextInt(ids.size());
//                qids[first++] = ids.get(ra);
//                //防止随机题目重复，已经添加的题号，在题库序号中就移除
//                ids.remove(ra);
//                System.out.println("Sqids = " + qids[i]);
//                if (questionBankIds.length-1>index){
//                    index++;
//                }
//            }
//            questions.setQuestionBanksId(null);
}




